﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Enter.Common
{
   public sealed class SafeSecurity
	{
		private static byte[] rgbIV = new byte[] { 0x14, 0x20, 0x06, 120, 0x71, 0xcb, 0x1d, 0x9f };

		/// <summary>
		/// DES加密字符串
		/// </summary>
		/// <param name="encryptString">待加密的字符串</param>
		/// <param name="encryptKey">加密密钥,要求为8位</param>
		/// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
		public static string EncryptDES(string pToEncrypt, string sKey)
		{
			try
			{
				DESCryptoServiceProvider des = new DESCryptoServiceProvider();
				byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
				//建立加密对象的密钥和偏移量
				//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
				//使得输入密码必须输入英文文本
				des.Key = ASCIIEncoding.UTF8.GetBytes(sKey);
				des.IV = rgbIV;
				MemoryStream ms = new MemoryStream();
				CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
				cs.Write(inputByteArray, 0,
					inputByteArray.Length);
				cs.FlushFinalBlock();
				StringBuilder ret = new StringBuilder();
				foreach (byte b in ms.ToArray())
				{
					ret.AppendFormat("{0:X2}", b);
				}
				return ret.ToString();
			}
			catch { return ""; }
		}

		/// <summary>
		/// DES解密字符串
		/// </summary>
		/// <param name="decryptString">待解密的字符串</param>
		/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
		/// <returns>解密成功返回解密后的字符串，失败返源串</returns>
		public static string DecryptDES(string pToDecrypt, string sKey)
		{
			try
			{
				DESCryptoServiceProvider des = new
					DESCryptoServiceProvider();
				byte[] inputByteArray = new byte
					[pToDecrypt.Length / 2];
				for (int x = 0; x < pToDecrypt.Length / 2; x++)
				{
					int i = (Convert.ToInt32
						(pToDecrypt.Substring(x * 2, 2), 16));
					inputByteArray[x] = (byte)i;
				}
				//建立加密对象的密钥和偏移量，此值重要，不能修改
				des.Key = ASCIIEncoding.UTF8.GetBytes(sKey);
				des.IV = rgbIV;
				MemoryStream ms = new MemoryStream();
				CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
				cs.Write(inputByteArray, 0, inputByteArray.Length);
				cs.FlushFinalBlock();

				//建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象
				StringBuilder ret = new StringBuilder();
				return System.Text.Encoding.Default.GetString(ms.ToArray());
			}
			catch { return ""; }
		}
	}
}
